package com.zrrd._11_network.tcp.no_01;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author WanJl
 * @version 1.0
 * @title Server03
 * @description 先读再写
 * @create 2023/10/22 16:43
 */
public class Server {
    /**
     * 服务器下载的方法
     * @param port
     * @param filePath
     */
    public static void download(int port,String filePath) throws IOException {
        ServerSocket server = new ServerSocket(port);
        Socket socket = server.accept();
        //获取来自客户端的数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //把数据保存到本地，文件输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        int b;
        //连读带写，先从网络读
        while ((b=bis.read())!=-1){
            //再写入到本地磁盘
            bos.write(b);
        }

        //向客户端发送反馈信息
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("上传成功....");
        bw.newLine();
        bw.flush();

        //释放资源
        bw.close();
        bos.close();
        socket.close();
        server.close();


    }

    public static void main(String[] args) throws IOException {
        download(10010,"E:/zs.txt");
    }
}
